package controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

public class UserServlet extends HttpServlet {

    // 重写方法 alt + insert

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");

        System.out.println("UserServlet");
        System.out.println("username: " + username);
        System.out.println("password: " + password);
        System.out.println("sex: " + sex);

        // resp 响应
//        resp.setContentType("text/html;charset=utf-8");
//        resp.setCharacterEncoding("utf-8");
//        PrintWriter out = resp.getWriter();
//        out.println(username);
//        out.println(password);
//        out.println(sex);

        // session  可以在多个servlet 里共享数据  用户的登录信息存在session
        req.getSession().setAttribute("username", "zhangsan");

        // req 放值
        List<User> users = new ArrayList<User>();
        User user = new User(1, "lisi", "123");
        users.add(user);
        User user1 = new User(2, "zangsan", "321");
        users.add(user1);
        req.setAttribute("users", users);
        req.setAttribute("username", username);
        req.setAttribute("password", password);
        req.setAttribute("sex", sex);
        // 转发  req、 重定向resp
        // 转发  url 不会改变
        req.getRequestDispatcher("user.jsp").forward(req, resp);

        // 重定向 url 会改变
//        resp.sendRedirect("user.jsp");
    }
}
